<template>
  <div class="contract">
    <van-nav-bar
      fixed
      border
      title="新建合同"
      left-arrow
      @click-left="goBack"
    />
    <van-cell-group>
      <van-field
        @click="confirmStatus = true"
        v-model="form.config"
        readonly
        required
        label="是否在园客户"
        is-link
        placeholder="请选择"
        :error-message="errors.config"
        input-align="right"
        error-message-align="right"
        @input="errors.config = ''"
      />
      <van-field
        v-if="form.in_park == 0"
        v-model="form.customer_name"
        :disabled="disabled"
        required
        clearable
        label="客户名称"
        placeholder="请输入"
        :error-message="errors.customer_name"
        input-align="right"
        error-message-align="right"
      />
      <van-field
        v-if="form.in_park == 1"
        v-model="form.customer_name"
        :disabled="disabled"
        required
        clearable
        label="客户名称"
        placeholder="搜索客户"
        :error-message="errors.customer_name"
        input-align="right"
        error-message-align="right"
        @input="getCustomer"
      />
      <van-field
        type="number"
        maxlength="11"
        v-model="form.mobile"
        :disabled="disabled"
        required
        clearable
        label="客户手机"
        placeholder="手机号用于登录客户端"
        :error-message="errors.mobile"
        input-align="right"
        error-message-align="right"
        @input="errors.mobile = ''"
      />
      <van-field
        v-model="form.certificate_number"
        :disabled="disabled"
        required
        clearable
        label="身份证号"
        placeholder="请输入"
        :error-message="errors.certificate_number"
        input-align="right"
        error-message-align="right"
        @input="errors.certificate_number = ''"
      />
      <van-field
        v-model="form.custom_industry_name"
        :disabled="disabled"
        readonly
        label="所属行业"
        is-link
        placeholder="请选择"
        :error-message="errors.custom_industry_name"
        input-align="right"
        error-message-align="right"
        @input="errors.custom_industry_name = ''"
        @click="industryStatus = true"
      />
      <van-field
        v-model="form.director_name"
        :disabled="disabled"
        required
        clearable
        is-link
        readonly
        label="厂长"
        placeholder="请选择"
        :error-message="errors.director_name"
        input-align="right"
        error-message-align="right"
        @input="errors.director_name = ''"
        @click="directorStatus = true"
      />
      <van-field
        :disabled="disabled"
        @click="calendarStatus = true"
        v-model="form.start_time"
        required
        clearable
        is-link
        placeholder="请选择"
        readonly
        label="起租日期"
        :error-message="errors.start_time"
        input-align="right"
        error-message-align="right"
        @input="errors.start_time = ''"
      />
      <van-field
        :disabled="disabled"
        @click="show = true"
        v-model="form.years"
        required
        clearable
        is-link
        placeholder="请选择"
        readonly
        label="选择租期"
        :error-message="errors.years"
        input-align="right"
        error-message-align="right"
        @input="errors.years = ''"
      />
      <van-field
        v-model="search"
        :disabled="disabled"
        required
        clearable
        label="选择房源"
        placeholder="输入如:A栋/1F/101"
        input-align="right"
        error-message-align="right"
        center
      >
        <template #button>
          <van-button size="small" @click="handeInput" color="#1375FF"
            >搜索房源</van-button
          >
        </template>
      </van-field>
      <!-- <van-field
        :disabled="disabled"
        required
        clearable
        label="选择房源"
        placeholder="搜索房号,如:A栋/1F/101"
        input-align="right"
        error-message-align="right"
        @input="handeInput"
      /> -->
      <div class="tag_box" v-if="form.room_name">
        <van-tag
          style="margin-right: 15px; margin-top: 10px"
          v-for="(item, index) in form.room_name"
          :key="index"
          closeable
          size="medium"
          color="#1375FF"
          @close="close(index)"
        >
          {{ item }}
        </van-tag>
      </div>
      <!-- <van-field
        class="textarea"
        v-model="form.title"
        type="textarea"
        placeholder=""
      /> -->
      <div class="tisp">
        温馨提示：<br />
        若客户曾在园区签约，输入客户名称，将为您匹配客户相关信息。<br />
        若客户与在园客户重名，请在名称上区分。
      </div>
    </van-cell-group>
    <van-button
      slot="action"
      size="small"
      type="danger"
      color="#1375FF"
      class="request-btn"
      @click="handle"
      >生成合同条款</van-button
    >
    <van-calendar
      v-model="calendarStatus"
      @confirm="onConfirm"
      :min-date="minDate"
      :max-date="maxDate"
      color="#1375FF"
    />
    <popupItem
      :show="show"
      :columns="lease"
      @config="config"
      @cancle="cancle"
    />
    <popupItem
      :show="confirmStatus"
      :columns="confirmArr"
      @config="configUser"
      @cancle="cancle"
    />
    <popupItem
      :show="industryStatus"
      :columns="industry"
      @config="configindustry"
      @cancle="cancle"
    />
    <popupItem
      :show="directorStatus"
      :columns="directors"
      @config="configdirector"
      @cancle="cancle"
    />
    <popupItem
      :show="customersStatus"
      :columns="customers"
      @config="configcustomers"
      @cancle="cancle"
    />
    <popupItem
      :show="listCustomerStatus"
      :columns="listCustomer"
      @config="configlistCustomer"
      @cancle="cancle"
    />

    <!-- <popupItem
      :show="RoomsStatus"
      :columns="Rooms"
      @config="configcustomers"
      @cancle="cancle"
    /> -->
    <checkBoxItem
      :show="RoomsStatus"
      :columns="Rooms"
      @cancle="cancle"
      @config="start_time"
    />
  </div>
</template>

<script>
import {
  NavBar,
  Image,
  Button,
  Cell,
  CellGroup,
  Field,
  Calendar,
  Tag,
  Checkbox,
  CheckboxGroup,
  Toast,
} from "vant";
import popupItem from "@/components/popup_item";
import checkBoxItem from "@/components/checkBox_item";
import { _debounce, _throttle } from "@/utils/debounce";
import moment from "moment";
import {
  checkoutEndMonth,
  checkoutHouseEndTime,
  contractSave,
  getRooms,
  contractCreate,
  getCustomerRead,
  searchCustomer,
} from "@/api/index";
export default {
  components: {
    [NavBar.name]: NavBar,
    [Image.name]: Image,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [Tag.name]: Tag,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Toast.name]: Toast,
    popupItem,
    checkBoxItem,
  },
  data() {
    return {
      moment,
      disabled: true,
      show: false,
      confirmStatus: false,
      calendarStatus: false,
      industryStatus: false,
      directorStatus: false,
      customersStatus: false,
      RoomsStatus: false,
      listCustomerStatus: false,
      form: {
        in_park: null,
        customer_id: "",
        customer_name: "",
        mobile: "",
        certificate_number: "",
        custom_industry_id: "",
        custom_industry_name: "",
        director_id: "",
        start_time: "",
        years: "",
        room_ids: [],
        room_name: [],
        title: "",
        date: "",
        lease: "",
        config: "",
        director_name: "",
      },
      errors: {
        title: "",
      },
      lease: ["1年", "2年"],
      confirmArr: ["是", "否"],
      customers: [],
      directors: [],
      industry: [],
      list: [],
      Rooms: [],
      listCustomer: [],
      Customer: [],
      search: "",
      arr: [],
      arr2: [],
    };
  },
  mounted() {
    document
      .querySelector("body")
      .setAttribute("style", "background-color:#fff");
    this.getContractCreate();
    if (this.$route.query.in_park) {
      this.form.in_park = this.$route.query.in_park;
      this.form.customer_id = this.$route.query.customer_id;
      this.form.customer_name = this.$route.query.customer_name;
      this.form.mobile = this.$route.query.mobile;
      this.form.certificate_number = this.$route.query.certificate_number;
      this.form.custom_industry_id = this.$route.query.custom_industry_id;
      this.form.director_id = this.$route.query.director_id;
      this.form.start_time = this.$route.query.start_time;
      this.form.years = this.$route.query.years[0];
      this.form.room_ids = this.$route.query.room_ids;
      this.form.room_name = this.$route.query.room_name;
      this.form.director_name = this.$route.query.director_name;
      this.form.custom_industry_name = this.$route.query.custom_industry_name;
    }
  },
  computed: {
    minDate() {
      let curDate = new Date(2020, 0, 1);
      let one = 0 * 24 * 3600 * 1000;
      let oneYear = curDate + one;
      return new Date(curDate);
    },
    maxDate() {
      let curDate = new Date().getTime();
      let one = 29 * 24 * 3600 * 1000;
      let oneYear = curDate + one;
      return new Date(oneYear);
    },
  },
  methods: {
    getCustomer: _throttle(async function (val) {
      try {
        if (this.form.customer_name) {
          this.Customer = await searchCustomer({
            keyword: this.form.customer_name,
          });
          if (this.Customer.length > 0) {
            this.listCustomer = this.Customer.map((item) => item.name);
            this.listCustomerStatus = true;
          } else {
            Toast({
              icon: "success",
              message: "暂无数据",
            });
          }
        }
      } catch (error) {
        this.$dialog.alert({
          title: "温馨提示",
          message: error.message,
        });
      }
    }, 2000),
    async getContractCreate() {
      this.list = await contractCreate();
      this.customers = this.list.customers.map((item) => item.name);
      this.directors = this.list.directors.map((item) => item.username);
      this.industry = this.list.industry.map((item) => item.value);
    },
    handeInput: _throttle(async function (val) {
      try {
        if (this.search) {
          this.Rooms = await getRooms({ keyword: this.search });
          if (this.Rooms.length > 0) {
            this.RoomsStatus = true;
          } else {
            this.RoomsStatus = false;
            Toast({
              icon: "success",
              message: "暂无数据",
            });
          }
        }
      } catch (error) {
        this.$dialog.alert({
          title: "温馨提示",
          message: error.message,
        });
      }
    }, 2000),
    // async handeInput(val) {
    //   try {
    //     if (val) {
    //       this.Rooms = await getRooms({ keyword: val });
    //       if (this.Rooms.length > 0) {
    //         this.RoomsStatus = true;
    //       } else {
    //          this.RoomsStatus = false;
    //         Toast({
    //           icon: "success",
    //           message: "暂无数据",
    //         });
    //       }
    //     }
    //   } catch (error) {
    //     this.$dialog.alert({
    //       title: "温馨提示",
    //       message: error.message,
    //     });
    //   }
    // },
    close(index) {
      if (this.form.room_name.indexOf(this.form.room_name[index]) != -1) {
        this.form.room_name.splice(
          this.form.room_name.indexOf(this.form.room_name[index]),
          1
        );
        this.arr.splice(this.arr.indexOf(this.arr[index]), 1);
      }

      if (this.form.room_ids.indexOf(this.form.room_ids[index]) != -1) {
        this.form.room_ids.splice(
          this.form.room_ids.indexOf(this.form.room_ids[index]),
          1
        );
        this.arr2.splice(this.arr2.indexOf(this.arr2[index]), 1);
      }
    },
    onConfirm(date) {
      this.form.start_time = moment(date).format("YYYY-MM-DD");
      this.calendarStatus = false;
    },
    configindustry(list, index) {
      this.form.custom_industry_name = list;
      this.form.custom_industry_id = this.list.industry[index].id;
      this.industryStatus = false;
    },
    configdirector(list, index) {
      this.directorStatus = false;
      this.form.director_name = list;
      this.form.director_id = this.list.directors[index].id;
    },
    async configlistCustomer(list, index) {
      this.listCustomerStatus = false;
      this.form.customer_name = list;
      this.form.customer_id = this.Customer[index].id;
      const res = await getCustomerRead({
        customer_id: this.Customer[index].id,
      });
      this.form.mobile = res.company_phone;
      this.form.certificate_number = res.certificate_number;
      this.form.custom_industry_id = res.custom_industry_id;
      this.form.director_name = res.director.username;
      this.form.director_id = res.director_id;
      if (res.industry) {
        this.form.custom_industry_name = res.industry.value;
      }
    },
    async configcustomers(list, index) {
      this.form.customer_name = list;
      this.form.customer_id = this.list.customers[index].id;
      this.customersStatus = false;
      const res = await getCustomerRead({
        customer_id: this.list.customers[index].id,
      });
      this.form.mobile = res.company_phone;
      this.form.certificate_number = res.certificate_number;
      this.form.custom_industry_id = res.custom_industry_id;
      this.form.director_name = res.director.username;
      this.form.director_id = res.director_id;
      this.form.custom_industry_name = res.industry;
    },
    start_time(list) {
      this.arr.push(list.map((item) => item.name));
      this.arr2.push(list.map((item) => item.rm_id));
      this.form.room_ids = Array.from(
        new Set(
          this.arr2
            .join()
            .split(",")
            .map((item) => item)
        )
      );
      this.form.room_name = Array.from(
        new Set(
          this.arr
            .join()
            .split(",")
            .map((item) => item)
        )
      );
      this.RoomsStatus = false;
    },
    configUser(list) {
      this.form.config = list;
      this.disabled = false;
      this.confirmStatus = false;
      if (list == "是") {
        this.form.in_park = 1;
        this.form.customer_name = "";
      } else {
        this.form.in_park = 0;
        this.form.customer_name = "";
      }
    },
    config(list) {
      this.form.years = list;
      this.show = false;
    },
    cancle(list) {
      this.show = false;
      this.confirmStatus = false;
      this.confirmStatus = false;
      this.industryStatus = false;
      this.directorStatus = false;
      this.customersStatus = false;
      this.listCustomerStatus = false;
      this.RoomsStatus = false;
    },
    // formatDate(date) {
    //   return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    // },
    goBack() {
      this.$router.back();
    },
    async handle() {
      try {
        if (!this.form.customer_name) {
          Toast({
            message: "请填写客户名称",
          });
          return;
        }
        if (!this.form.mobile) {
          Toast({
            message: "请填写手机号",
          });
          return;
        }
        if (!this.form.certificate_number) {
          Toast({
            message: "请填写身份证号",
          });
          return;
        }
        if (!this.form.director_id) {
          Toast({
            message: "请填写厂长",
          });
          return;
        }
        if (!this.form.years) {
          Toast({
            message: "请选择租期",
          });
          return;
        }
        if (!this.form.start_time) {
          Toast({
            message: "请选择起租日期",
          });
          return;
        }
        if (this.form.room_name.length <= 0) {
          Toast({
            message: "请选择房源",
          });
          return;
        }

        const res = await checkoutEndMonth({
          start_time: this.form.start_time,
          years: this.form.years[0],
        });
        if (res == false) {
          try {
            const l = await checkoutHouseEndTime({
              start_time: this.form.start_time,
              years: this.form.years[0],
              room_ids: this.form.room_ids,
            });
            if (l.name) {
              this.$dialog
                .confirm({
                  title: "温馨提示",
                  message: `${l.name}租赁到期时间最晚为${l.date}，自动为您签约至该日，是否继续`,
                })
                .then(async () => {
                  this.$router.push({
                    path: "/clause",
                    query: {
                      id: this.DormId,
                      type: 1,
                      years: this.form.years[0],
                      in_park: this.form.in_park,
                      customer_id: this.form.customer_id,
                      customer_name: this.form.customer_name,
                      mobile: this.form.mobile,
                      certificate_number: this.form.certificate_number,
                      custom_industry_id: this.form.custom_industry_id,
                      director_id: this.form.director_id,
                      start_time: this.form.start_time,
                      room_ids: this.form.room_ids,
                      room_name: this.form.room_name,
                      director_name: this.form.director_name,
                      custom_industry_name: this.form.custom_industry_name,
                    },
                  });
                });
            } else {
              this.$router.push({
                path: "/clause",
                query: {
                  id: this.DormId,
                  type: 1,
                  years: this.form.years[0],
                  in_park: this.form.in_park,
                  customer_id: this.form.customer_id,
                  customer_name: this.form.customer_name,
                  mobile: this.form.mobile,
                  certificate_number: this.form.certificate_number,
                  custom_industry_id: this.form.custom_industry_id,
                  director_id: this.form.director_id,
                  start_time: this.form.start_time,
                  room_ids: this.form.room_ids,
                  room_name: this.form.room_name,
                  director_name: this.form.director_name,
                  custom_industry_name: this.form.custom_industry_name,
                },
              });
            }
          } catch (error) {
            this.show = false;
            this.$dialog.alert({
              title: "温馨提示",
              message: error.message,
            });
          }
        } else {
          this.$dialog
            .confirm({
              title: "温馨提示",
              message:
                "根据规定，不可12月、1月、2月退租,将自动为您延续至3月31号,是否继续?",
            })
            .then(async () => {
              // on confirm
              try {
                const l = await checkoutHouseEndTime({
                  start_time: this.form.start_time,
                  years: this.form.years[0],
                  room_ids: this.form.room_ids,
                });
                if (l.name) {
                  this.$dialog
                    .confirm({
                      title: "温馨提示",
                      message: `${l.name}租赁到期时间最晚为${l.date}，自动为您签约至该日，是否继续`,
                    })
                    .then(async () => {
                      this.$router.push({
                        path: "/clause",
                        query: {
                          id: this.DormId,
                          type: 1,
                          years: this.form.years[0],
                          in_park: this.form.in_park,
                          customer_id: this.form.customer_id,
                          customer_name: this.form.customer_name,
                          mobile: this.form.mobile,
                          certificate_number: this.form.certificate_number,
                          custom_industry_id: this.form.custom_industry_id,
                          director_id: this.form.director_id,
                          start_time: this.form.start_time,
                          room_ids: this.form.room_ids,
                          room_name: this.form.room_name,
                          director_name: this.form.director_name,
                          custom_industry_name: this.form.custom_industry_name,
                        },
                      });
                    });
                } else {
                  this.$router.push({
                    path: "/clause",
                    query: {
                      id: this.DormId,
                      type: 1,
                      years: this.form.years[0],
                      in_park: this.form.in_park,
                      customer_id: this.form.customer_id,
                      customer_name: this.form.customer_name,
                      mobile: this.form.mobile,
                      certificate_number: this.form.certificate_number,
                      custom_industry_id: this.form.custom_industry_id,
                      director_id: this.form.director_id,
                      start_time: this.form.start_time,
                      room_ids: this.form.room_ids,
                      room_name: this.form.room_name,
                      director_name: this.form.director_name,
                      custom_industry_name: this.form.custom_industry_name,
                    },
                  });
                }
              } catch (error) {
                this.show = false;
                this.$dialog.alert({
                  title: "温馨提示",
                  message: error.message,
                });
              }
            })
            .catch(() => {
              // on cancel
            });
        }
      } catch (error) {
        this.$dialog.alert({
          title: "温馨提示",
          message: error.message,
        });
      }
      // this.$dialog
      //   .confirm({
      //     title: "温馨提示",
      //     message: "根据规定，不可12月、1月、2月退租",
      //   })
      //   .then(() => {
      //     // on confirm
      //     this.$router.push("/clause");
      //   })
      //   .catch(() => {
      //     // on cancel
      //   });
    },
  },
};
</script>

<style lang="less" scoped>
.tisp {
  color: #c8c9cc;
  font-size: 14px;
  width: 95%;
  margin: 10px auto;
  padding-bottom: 10px;
}
.request-btn {
  width: 142px;
  height: 35px;
  border-radius: 17px;
  font-size: 16px;
  border: none;
  margin: 20px auto;
  display: flex;
  justify-content: center;
  // position: fixed;
  // bottom: 80px;
  // left: 50%;
  // transform: translateX(-50%);
  // z-index: 2;
}
.tag_box {
  width: 90%;
  margin: 10px auto;
  background: #f9f9f9;
  // height: 80px;
  padding: 10px;
}
.contract {
  padding-top: 42px;
  width: 95%;
  margin: 0 auto;
  // background: #fff;
}
@media (min-width: 750px) {
  .tisp {
    color: #c8c9cc;
    font-size: 14px;
    width: 95%;
    margin: 10px auto;
    padding-bottom: 10px;
  }
  .request-btn {
    width: 142px;
    height: 35px;
    border-radius: 17px;
    font-size: 16px;
    border: none;
    margin: 20px auto;
    display: flex;
    justify-content: center;
    // position: fixed;
    // bottom: 80px;
    // left: 50%;
    // transform: translateX(-50%);
    // z-index: 2;
  }
  .tag_box {
    width: 90%;
    margin: 10px auto;
    background: #f9f9f9;
    // height: 80px;
    padding: 10px;
  }
  .contract {
    padding-top: 42px;
    width: 95%;
    margin: 0 auto;
    // background: #fff;
  }
}
</style>